package lishizheng.demo06;

//不安全的买票
public class UnsafeBuyTicket {

    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();

        new Thread(buyTicket,"小米").start();
        new Thread(buyTicket,"小明").start();
        new Thread(buyTicket,"黄牛").start();
    }
}

class  BuyTicket implements Runnable{
    private  int ticketNums = 10;
    boolean flag = true;
    @Override
    public void run() {

        //模拟延时
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //买票
        while (flag){
            buy();
        }
    }

    //synchronized同步方法，锁的是this
    private  synchronized void buy(){
        if(ticketNums <= 0) {
            flag = false;
            return;
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " 拿到" + ticketNums--);
    }
}
